<template>
    <div class="react-container">
        <div ref="startBox" class="rect rect1 draggable">start</div>
        <div ref="endBox" class="rect rect2 draggable">end</div>
        <svg class="connector" :style="svgStyle" v-if="show">
            <path :d="pathD" stroke="#999" stroke-width="1" fill="none" />
        </svg>
    </div>
</template>
<script setup>
import { onMounted, ref, inject, onActivated, onDeactivated } from 'vue'
import usePageVisibility from '@/hooks/usePageVisibility'

const { isVisible } = usePageVisibility()

const global = inject('global')

onMounted(() => {
    global.$emitter.on('RouterScroll', () => {
        updatePath()
    })
    updatePath()
})

const show = ref(true)

//组件被激活
onActivated(() => {
    show.value = true
    updatePath()
})

//组件被隐藏
onDeactivated(() => {
    show.value = false
})

const startBox = ref(null)
const endBox = ref(null)

const svgStyle = {
    position: 'fixed',
    top: '0',
    left: '0',
    width: '100%',
    height: '100%',
    pointerEvents: 'none',
}

const pathD = ref('')

window.addEventListener('resize', () => {
    updatePath()
})

document.addEventListener('visibilitychange', () => {
    console.log(isVisible.value)
})

const updatePath = () => {
    if (!startBox.value || !endBox.value) return

    const startRect = startBox.value.getBoundingClientRect()
    const endRect = endBox.value.getBoundingClientRect()

    // 计算中心点的X轴位置
    let _startX = startRect.left + window.scrollX + startRect.width
    let _endX = endRect.left + window.scrollX

    let startX = _startX,
        endX = _endX

    // 假设转折点位于两者的中间位置

    // 垂直方向上，连接线从一个div的底部/顶部到另一个div的顶部/底部
    let _startY = startRect.bottom + window.scrollY - startRect.height / 2
    let _endY = endRect.top + window.scrollY + startRect.height / 2
    let startY = _startY
    let endY = _endY

    let midX = (startX + endX) / 2
    if (startX > endX) {
        endX = endRect.left + window.scrollX + endRect.width
        startX = startRect.left + window.scrollX
        if (_startX - _endX < startRect.width + endRect.width) {
            startX = startRect.left + window.scrollX
            endX = endRect.left + window.scrollX
            midX = startRect.left + window.scrollX - 20
            if (endX < startX) {
                midX = endRect.left + window.scrollX - 20
            }
        }
    }

    // 构造路径
    pathD.value = `M ${startX},${startY} L ${midX},${startY} L ${midX},${endY} L ${endX},${endY}`
}
</script>
<style lang="less" scoped>
.react-container {
    position: relative;
    width: 100%;
    height: 400px;
    overflow: hidden;
    background-color: fade(#fff, 5%);
    padding: 20px 80px;
    .rect {
        position: relative;
        width: 200px;
        height: 100px;
        background: fade(#fff, 20%);
    }
}
</style>
